

#import "NSArray+JSONReadWrite.h"

@implementation NSArray (JSONReadWrite)


/// 读取JSON数据
+ (NSArray *)JSONWithContentsOfFile:(NSString *)filePath {
    NSError *error = nil;
    NSData *jsonData = [NSData dataWithContentsOfFile:filePath options:0 error:&error];
    if (!jsonData) {
        NSLog(@"NSArray无法读取文件: %@, 错误: %@", filePath, error.localizedDescription);
        return nil;
    }
    NSArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    if (!json || ![json isKindOfClass:NSArray.class]) {
        NSLog(@"JSON数组解析NSArray失败: %@", error.localizedDescription);
        return nil;
    }
    return json;
}

/// 写入JSON数据
- (BOOL)writeToJSONFile:(NSString *)filePath atomically:(BOOL)atomically {
    NSArray *json = self ?: @[];
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:&error];
    if (!jsonData) {
        NSLog(@"JSON序列化NSArray失败: %@", error.localizedDescription);
        return NO;
    }
    BOOL res = [jsonData writeToFile:filePath atomically:YES];
    NSLog(@"--->JSON写入NSArray: %@ 路径: %@", res ? @"成功" : @"失败", filePath);
    return res;
}

@end
